package com.hyhy.hycloud.uaa.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyhy.hycloud.commons.dto.InvokeResult;
import com.hyhy.hycloud.uaa.UaaErrorDescribable;
import com.hyhy.hycloud.uaa.UaaErrorType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * AuthenticationException写入到PrintWriter
 *
 * @author Xuegui Yuan
 * @date 2018-09-19
 */
public class AuthenticationExceptionWriter {

    public static void write(PrintWriter out, AuthenticationException e, ObjectMapper objectMapper) throws IOException {
        String result;
        InvokeResult<?> invokeResult;
        if (e instanceof UaaErrorDescribable) {
            invokeResult = InvokeResult.error(((UaaErrorDescribable) e).getErrorType().toRuntimeException());
        } else if (e instanceof BadCredentialsException) {
            invokeResult = InvokeResult.error(UaaErrorType.ACCOUNT_PASSWORD_ERROR.toRuntimeException());
        } else {
            invokeResult = InvokeResult.error(UaaErrorType.UNAUTHORIZED_ERROR.toRuntimeException());
        }
        result = objectMapper.writeValueAsString(invokeResult);
        out.write(result);
        out.flush();
        out.close();
    }
}
